package com.violet.common.util;

import org.yaml.snakeyaml.Yaml;

import java.io.FileInputStream;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;


public class YmlUtils {

    private static final String YML = "application.yml";
    private static final Map<String, Object> YML_MAP = new ConcurrentHashMap<>();

    static {
        getApplicationYml(YML);
        getApplicationYml(getActiveYml());
    }
 
    private static String getActiveYml() {
        String[] strings = YML.split("\\.");
        return strings[0] + "-" + YML_MAP.get("spring.profiles.active") + "." + strings[1];
    }
 
    private static void getApplicationYml(String yml) {
        Yaml yaml = new Yaml();
        URL url = ClassLoader.getSystemResource(yml);
        try (FileInputStream in = new FileInputStream(url.getFile())) {
            Map<String, Object> map = cast(yaml.loadAs(in, Map.class));
            switchToMap("", map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    private static void switchToMap(String myKey, Map<String, Object> map) {
        Iterator<String> it = map.keySet().iterator();
        String tmpkey = myKey;
        while (it.hasNext()) {
            String key = it.next();
            myKey = tmpkey + key;
            Object value = map.get(key);
            if (value instanceof Map) {
                switchToMap(myKey.concat("."), cast(value));
            } else if (Objects.nonNull(value)) {
                YML_MAP.put(myKey, value);
                //System.out.println(myKey + "->" + map.get(key));
            }
        }
    }
 
    @SuppressWarnings("unchecked")
    private static <T> T cast(Object obj) {
        return (T) obj;
    }
 
    public static <T> T get(String key) {
        return cast(YML_MAP.get(key));
    }
 
    public static String getString(String key) {
        return String.valueOf(YML_MAP.get(key));
    }

    public static List<String> getStringList(String key) {
        return (List<String>)YML_MAP.get(key);
    }
 
    public static void main(String[] args) {
        String jdbc = getString("spring.datasource.url");
        System.out.println(jdbc);
    }
 
}